var jsonForm = function(url) {	
	emp.$(".loading").css("display", "block");
	emp.$(".loading").css("z-index", "2000");
		emp.$('#modalTitle').html("");
		emp.$('#modalBody').html("");
		
		var modal = getModalData(url);
		
		emp.$('#modalTitle').html(modal.metadata.header.title);
		emp.$('#modalBody').html(modal.content);	
	emp.$(".loading").css("display", "none");
	unblock();
};

function fetchJson(url) {
	var json = {};
	emp.$.ajax({
		url: url,
		dataType: "text",
		success: function(data) {
			json = emp.$.parseJSON(escapeNewLine(data));
		},
		async:false
	});
	
	return json;
};

var selectedRow = function(gridId) {
		var selRow = {};
		if ($('#' + gridId).jqGrid('getGridParam','selrow')) {
			selRow.rowId = $('#' + gridId).jqGrid('getGridParam','selrow');
			selRow.rowIdx = $('#' + gridId).getInd(selRow.rowId);
			selRow.engineIdx = selRow.rowIdx - 1;
//			var data = emp.configManager.config.mapEngines[selRow.engineIdx].properties || {};
//			selRow.data = data;
		}
		return selRow;
}; 

function getEngineProperties(id) {
	var properties = {};
	if (emp.configManager.config.mapEngines[id].properties) {
		properties = emp.configManager.config.mapEngines[id].properties || {};		
	}
	return properties;
};

function saveSettings(url) {
	var row = {};
	var rowId  = $('#grid-map-engine').jqGrid('getGridParam','selrow');
	var rowIdx = $('#'+ $.jgrid.jqID(rowId))[0].rowIndex;
	var name   = $('#grid-map-engine').jqGrid('getCell', rowId, 'name');
	var rowUrl = $('#grid-map-engine').jqGrid('getCell', rowId, 'url');				  		
	var json = convertFormToJson(emp.$("#modalSubmitForm"));
	var jsonStr = JSON.stringify(json); 

	row.id = rowId;
	row.idx = rowIdx;
	row.name = name;
	row.url = rowUrl;
	row.properties = json;
	
	var data = JSON.stringify(row);
	
	url = url + "/" + name+"?properties="+jsonStr;
	
	emp.$.ajax({
		url: url,
		type: "POST",
		data: data,
		contentType: "application/json; charset-utf-8",
		dataType: "json",
		success: function(data) {
			json = JSON.stringify(data);			
			updateEmpManager(data);			
			reloadMapEngineGrid();
		},
		async:false
	});
	
	return json;
};

function updateEmpManager(data) {
	emp.configManager.config.mapEngines[selectedRow('grid-map-engine').engineIdx].properties = emp.configManager.config.mapEngines[selectedRow('grid-map-engine').engineIdx].properties || {};
	emp.configManager.config.mapEngines[selectedRow('grid-map-engine').engineIdx].properties = data;
};

function convertFormToJson(form) {	
	var jsonObj = {};
	
	form.find('input, select').each(function() {
		var val;
		if (!this.name) {
			return;
		}
		if ('radio' === this.type) {
			if (jsonObj[this.name]) {
				return;
			}
			jsonObj[this.name] = (this.checked) ? this.value : '';
		} else if ('checkbox' === this.type) {
			val = jsonObj[this.name];
			
			if (!this.checked) {
				if (!val) {
					jsonObj[this.name] = "false";
				}
			} else {
				jsonObj[this.name] = (typeof val === 'string') ? [val, this.value] : ($.isArray(val)) ? $.merge(val, [this.value]) : this.value; 
			}
		} else {
			jsonObj[this.name] = this.value;
		}
	});
	
	return jsonObj;
};

function getModalData(url) {	
	var modal = fetchJson(url);
	if (!isEmpty(modal)) {
		modal.content = buildForm(modal);
	} else {
		modal = getErrorModal();
	}
	
	return modal;
};

function getErrorModal() {
	var modal = {};
	modal.metadata = {};
	modal.metadata.header = {};
	modal.metadata.header.title="Additional Configurations";
	
	var body = "<div id='" + modal.metadata.header + "' class='horizontal-form well-lg'>";	
	body += "<p><h3>No additional configurations are available</h3></p>";		
	body += "</div>";

	modal.content = body;
	
	$('.modal-footer').hide();
	
	return modal;
};

/**
 * Returns true if given value is neither "undefined" nor null
 */
var isSet = function (value) {
  return !(value == undefined || value == '');
};

function isEmpty(jsObj) {
	if (jsObj == null) { return true; }	
	if (jsObj.length > 0) { return false; };	
	if (jsObj.length === 0) { return true; };
	
	for (var key in jsObj) {
		if (jsObj.hasOwnProperty(key)) {
			return false;
		}
	}	
	return true;
};

function replaceWhitespace(string, delim) {
	if (!isSet(string)) {
		return '';
	} else {
		string = string.trim();
	}
	
	delim = (isSet(delim)) ? delim : "_";	
	string = '' + string;
	    
	if (!string) {
	    return '';
	}	    
	return string.replace(/ /g, delim);
};

var escapeHTML = function (string) {
    if (!isSet(string)) {
      return '';
    }
    string = '' + string;
    if (!string) {
      return '';
    }
    return string
      .replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#x27;')
      .replace(/\//g, '&#x2F;');
};

var escapeNewLine = function(string) {
	if (!isSet(string)) {
	      return '';
	}
	return string.replace(/\r?\n|\r/g, '');
};

var escapeWhitespace = function(string) {
	if (!isSet(string)) {
	      return '';
	}
	return string
	.replace(/\s/g, '');
};

var buildForm = function(json) {
	var html = "<div id='genForm' class='horizontal-form well-sm'>" 
			+ "<form id='modalSubmitForm' name='modalSubmitForm' class='form-horizontal'>";	
	html += buildFormGroups(json.metadata.header.title, json.properties);
	html += "</form></div>";
	
	return html;
}; 

function buildFormGroups(id, inputs) {
	var htmlInputs = "";
	var i = 0;
	for (var prop in inputs) {		
		var obj = inputs[prop];
		var component = {};
		id = replaceWhitespace(id,"_");			
		var componentId = replaceWhitespace(id + "_" + obj.label); 
		//var componentName  = replaceWhitespace(obj.label);
		var componentName  = replaceWhitespace(obj.name);
		var componentValue = (emp.configManager.config.mapEngines[selectedRow('grid-map-engine').engineIdx].properties) 
								? emp.configManager.config.mapEngines[selectedRow('grid-map-engine').engineIdx].properties[componentName] 
								: "";
		
		component.parentid = id;
		component.id    = componentId;
		component.name  = componentName;
		component.value = componentValue;
		component.type  = obj.type;
		component.label = obj.label;		
		component.propertyName = obj.name;
		
		if (component.type == "checkbox") {
			
		}
		
		htmlInputs += "<div id='" + id + "' class='form-group'>";		
			htmlInputs += buildInnerModal(component);
		htmlInputs += "</div>"; 
		i++;
	}
	return htmlInputs;
};

function buildInnerModal(component) {
	var innerDiv = "";
	innerDiv += buildModalLabel(component);
	innerDiv += buildInputDiv(component);
	return innerDiv;
};

var buildModalLabel = function(component) {
	return "<label class='col-md-3 control-label' for='" + component.id + "'>" + component.label + ":</label>";	
};

var buildInputDiv = function(component) {
	var colClass = "col-md-8";
	var checked = "";
	component.format = (component.type == "checkbox" && isSet(component.format)) ? component.format : "style='margin-left: -240px;";	
	if (component.type == "checkbox" && isSet(component.format)) {
		colClass = "col-md-1";
		component.id += "_cb";		
		if (component.value == "true") {
			checked = "checked";
		}
	}	
	component.value  = (isSet(component.value)) ? component.value : "";
	
	var inputDiv = "<div class='" + colClass + "'>" 
		   + "<input class='form-control' " 		+	   
		   		"id='" + component.id 				+ 
		   		"' name='" + component.name 		+ 
		   		"' type='" + component.type + "'" 	+
		   		"' value='" + component.value + "'"	+
		   		" " + checked + " " 				+
		   		component.lblFormat +"' />" 		+ 
		   	"</div>";
	
	return inputDiv;
};

function getRowByIndex(index) {
	var row = emp.$('#datatable tr').eq(index);
	return row;
};

function getUrl(row) {
	var url = row.find('td:last-child').text();	
	
	if (url.match(/\/$/)) {
		url = url.replace(/\/$/, "");
	}
	
	var pos = url.lastIndexOf("/");
	var mod = getModifier(url.substring(pos, url.length));
	url = url.substring(0, pos) + "/schema" + mod + ".json";	
	
	return url;
};

function getModifier(str) {
	var modifier = "";
	var dash = str.lastIndexOf("-");
	var dot  = str.lastIndexOf(".");
	modifier = (dash >= 0 && dot >= 0) ? str.substring(dash,dot) : "";
	
	return modifier;
};
	
function launchSettingsModal(row) {
	block();
	var url = getUrl(row);
	jsonForm(url);
	emp.$('#myModal').modal();
};

function block() {
	emp.$.blockUI({overlayCSS: {backgroundColor: '#c9c9c9'},message: null, fadeIn: 0});
};

function unblock() {
	emp.$.unblockUI();
};

function loadingGif(isActive) {
	if (isActive == true) {
		emp.$('body').addClass("loading");
	} else {
		emp.$('body').removeClass("loading");
	}
};

function endswith(string, suffix) {
	return str.match(suffix + "$") == suffix;
};

$(document).on("click", "#modalSubmitForm input[type='checkbox']", function(event) {
	if ($(this).is(':checked')) {
		$(this).val("true");
	} else {
		$(this).val("false");
	}
});

